var gameCellArray=new Array();//棋盘所有坐标集合
var foodArray=["#icon-cherry","#icon-pineapple","#icon-blueberry","#icon-strawberry","#icon-mango","#icon-hamimelon","#icon-peach",
"#icon-pitaya","#icon-mangosteen","#icon-litchi","#icon-orange","#icon-banana","#icon-apple","#icon-lemon","#icon-grape","#icon-watermelon","#icon-pear"];
var snakeLocationArray=[];//当前蛇的全部身体所在的坐标集合,索引从0开始,对应蛇的从头到尾
var snakeNowDirection=2;//当前移动方向,1=上,2=右,3=下,4=左
var snakeFutureDirection=2;//将要移动的方向
var foodLocation={x:-1,y:-1};//记录食物坐标
//初始化游戏
function gameInit(){
    //初始化所有坐标
    for(var i=0;i<40;i++){
        //gameCellArray[i]=new Array();
        for(var j=0;j<40;j++){
            gameCellArray.push([i,j]);
        }
    }
    //清空已有坐标集合
    snakeLocationArray.splice(0,snakeLocationArray.length);  
    //初始化所有表格内容
    /*
    var trs=$("table.game-zone-table tr").each(function(i,n){
        //console.log(i+"__*__"+n.DOCUMENT_NODE);
        var tds=$(n).find('td').each(function(j,m){
             $(m).html('');
             $(m).attr("title","("+i+","+j+")");
             $(m).attr("name","area_"+i+"_"+j);
            // if((i+1)%2==0){
            //     if((j+1)%2==0){
            //         $(m).css({"background-color":"#9eb9af"});
            //     }else{
            //         $(m).css({"background-color":"#d49898"});
            //     }
            // }else{
            //     if((j+1)%2==0){
            //         $(m).css({"background-color":"#d49898"});
            //     }else{
            //         $(m).css({"background-color":"#9eb9af"});
            //     }
            // }
        });
    });*/
    //*******开始初始化数据*******/
    var snake_head='<div id="snake_2_0" style="left:40px;top:2.5px;" data-offset="2.5" class="snake-head">-&nbsp;&nbsp;<em class="snake-head-eyel"></em><em class="snake-head-eyer"></em></div>';
    var snake_body='<div id="snake_1_0" style="left:20px;top:2.5px;" data-offset="2.5" class="snake-body">--</div>';
    var snake_tail='<div id="snake_0_0" style="left:0px;top:5px;" data-offset="5" class="snake-tail">-</div>';
    var snakeObj_head =new Snake({
        oldMoveDir:2,
        newMoveDir:2,
        oldRotateDir:2,
        newRotateDir:2,
        coordOldX:2,
        coordOldY:0,
        coordNewX:2,
        coordNewY:0,
        offsetLeft:0,
        offsetTop:2.5
    });
    var snakeObj_body =new Snake({
        oldMoveDir:2,
        newMoveDir:2,
        oldRotateDir:2,
        newRotateDir:2,
        coordOldX:1,
        coordOldY:0,
        coordNewX:1,
        coordNewY:0,
        offsetLeft:0,
        offsetTop:2.5
    });
    var snakeObj_tail =new Snake({
        oldMoveDir:2,
        newMoveDir:2,
        oldRotateDir:2,
        newRotateDir:2,
        coordOldX:0,
        coordOldY:0,
        coordNewX:0,
        coordNewY:0,
        offsetLeft:0,
        offsetTop:5
    });
    $("#game-container").append(snake_tail);
    $("#game-container").append(snake_body);
    $("#game-container").append(snake_head);
    snakeObj_head.element=$("#snake_2_0");
    snakeObj_body.element=$("#snake_1_0");
    snakeObj_tail.element=$("#snake_0_0");
    snakeLocationArray.push(snakeObj_head);
    snakeLocationArray.push(snakeObj_body);
    snakeLocationArray.push(snakeObj_tail);
    //snakeLocationArray.push([2,0]);//插入蛇头
    //snakeLocationArray.push([1,0]);//插入蛇身
    //snakeLocationArray.push([0,0]);//插入蛇尾
    gameCellArray.splice([0,0],1);
    gameCellArray.splice([1,0],1);
    gameCellArray.splice([2,0],1);
    //生成食物
    createFood();
    //debugger
   
}
//移动
function snakeMove(){   
    //上下移动时,X轴不变,Y轴++或--
    //左右移动时,Y轴不变,X轴++或--
    //循环蛇的全部身体,依次变换位置;
    for(var i=0;i<snakeLocationArray.length;i++){
        var snakeObj=snakeLocationArray[i];
        var oldX=snakeObj.coordOldX;//此位置的X坐标-移动前
        var oldY=snakeObj.coordOldY;//此位置的Y坐标-移动前
        var newY=-1 ,newX=-1;//定义移动后的新位置的坐标
        snakeNowDirection=snakeObj.oldMoveDir;
        if(i==0)snakeObj.newMoveDir=snakeFutureDirection;
        moveDirection=snakeObj.newMoveDir;
        //原移动方向和新移动方向不能冲突,这里容错一下,如果冲突,就保持移动方向不变,(也就是不能原地掉头)
        if(snakeNowDirection==1&&moveDirection==3)moveDirection=1;
        if(snakeNowDirection==2&&moveDirection==4)moveDirection=2;
        if(snakeNowDirection==3&&moveDirection==1)moveDirection=3;
        if(snakeNowDirection==4&&moveDirection==2)moveDirection=4;
        snakeObj.newMoveDir=moveDirection;
        if(moveDirection==1){//向上运动
            newY=oldY-1;//Y轴-1
            newX=oldX;//X轴不变
            if(newY<0){
                alert("Game Over !");
                if(snakeInterval!=null)clearInterval(snakeInterval);
                break;
            }else{
                //if()
            }
        }else if(moveDirection==2){//向右运动
            newY=oldY;//Y轴不变
            newX=oldX+1;//X轴+1
            if(newX>39){
                alert("Game Over !");
                if(snakeInterval!=null)clearInterval(snakeInterval);
                break;
            }else{

            }
        }else if(moveDirection==3){//向下运动
            newY=oldY+1;//Y轴+1
            newX=oldX;//X轴不变
            if(newY>39){ 
                alert("Game Over !");
                if(snakeInterval!=null)clearInterval(snakeInterval);
                break;
            }else{

            }
        }else if(moveDirection==4){//向左运动
            newY=oldY;//Y轴不变
            newX=oldX-1;//X轴-1
            if(newX<0){
                alert("Game Over !");
                if(snakeInterval!=null)clearInterval(snakeInterval);
                break;
            }else{
               
            }
        }
        //移动一格
        var oldTop=$(snakeObj.element).data('offset');
        $(snakeObj.element).css({"left":(newX*20)+"px","top":(newY*20+oldTop)+"px"});   
        var isEatedFood=false;
        if(i==0){ 
            if(newX==foodLocation.x && newY==foodLocation.y){
                isEatedFood=true;
                var nowScore=$("#score-show").html();
                $("#score-show").html(nowScore++);
                //吃到食物
                setTimeout(() => {
                    $(".food-position").addClass('eatfood');
                    $(".food-position").remove();
                     //生成新食物
                    createFood();
                }, 2);
                var snake_new_body='<div id="snake_'+oldX+'_'+oldY+'" style="left:'+(oldX*20)+'px;top:'+(oldY*20+2.5)+'px;" data-offset="2.5" class="snake-body">··</div>';
                var snakeObj_new_body =new Snake({
                    oldMoveDir:moveDirection,
                    newMoveDir:moveDirection,
                    oldRotateDir:2,
                    newRotateDir:2,
                    coordOldX:oldX,
                    coordOldY:oldY,
                    coordNewX:newX,
                    coordNewY:newY,
                    offsetLeft:0,
                    offsetTop:2.5
                });
                $("#game-container").append(snake_new_body);
                snakeObj_new_body.element=$("#snake_"+oldX+"_"+oldY);
                if(snakeObj.oldRotateDir==1){
                    $(snakeObj_new_body.element).css({'-webkit-transform':'rotate(-90deg)'});
                }else if(snakeObj.oldRotateDir==3){
                    $(snakeObj_new_body.element).css({'-webkit-transform':'rotate(90deg)'});
                }else if(snakeObj.oldRotateDir==4){
                    $(snakeObj_new_body.element).css({'-webkit-transform':'rotate(180deg)'});
                }
                snakeLocationArray.splice(1,0,snakeObj_new_body);
                //if(snakeInterval!=null)clearInterval(snakeInterval);
                //break;
                //snakeInterval=setInterval(function(){snakeMove();},snakeMoveSpeed);   
                //newX=oldX,newY=oldY;           
            }
        }
        //转向
        turnDirection(snakeObj,snakeNowDirection,moveDirection);
        /*
        $(snakeObj.element).css({
            "transform":"translateX(20);",
            "transition":"transform 300ms",
            "-webkit-transform":"translateX(20);",
            "-webkit-transition":"transform 300ms",
        });*/
        //改变坐标和ID和方向
        snakeLocationArray[i].coordOldX=newX;
        snakeLocationArray[i].coordOldY=newY;
        snakeLocationArray[i].oldMoveDir=snakeLocationArray[i].newMoveDir;
        snakeLocationArray[i].newMoveDir=moveDirection;
        $(snakeObj.element).attr('id','snake_'+newX+'_'+newY);
        //snakeNowDirection=snakeLocationArray[i].oldMoveDir;
        //调整地图坐标
        gameCellArray.push([newX,newY]);//添加新坐标
        if(!isEatedFood){
            gameCellArray.splice([oldX,oldY],1);//移除旧坐标
        }else{
            if(snakeInterval!=null)clearInterval(snakeInterval);
            snakeInterval=setInterval(function(){snakeMove();},snakeMoveSpeed); 
            break;
        }
        //根据当前蛇身和下一个蛇身判断出下一个蛇身将要移动的方向
        if((i+1)<snakeLocationArray.length){
            var nextX=snakeLocationArray[i+1].coordOldX;
            var nextY=snakeLocationArray[i+1].coordOldY;
            if(nextX==oldX){
                if(nextY>oldY){
                    snakeLocationArray[i+1].oldMoveDir=snakeLocationArray[i+1].newMoveDir;
                    snakeLocationArray[i+1].newMoveDir=1;
                }
                if(nextY<oldY){
                    snakeLocationArray[i+1].oldMoveDir=snakeLocationArray[i+1].newMoveDir;
                    snakeLocationArray[i+1].newMoveDir=3;
                }
            }
            if(nextY==oldY){
                if(nextX>oldX){
                    snakeLocationArray[i+1].oldMoveDir=snakeLocationArray[i+1].newMoveDir;
                    snakeLocationArray[i+1].newMoveDir=4;
                }
                if(nextX<oldX){
                    //moveDirection=2;
                    //snakeNowDirection=2;
                    snakeLocationArray[i+1].oldMoveDir=snakeLocationArray[i+1].newMoveDir;
                    snakeLocationArray[i+1].newMoveDir=2;
                }
            }
        }
    }
}
//生成从minNum到maxNum的随机数
function randomNum(minNum,maxNum){ 
    switch(arguments.length){ 
        case 1: 
            return parseInt(Math.random()*minNum+1,10); 
        break; 
        case 2: 
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
        break; 
            default: 
                return 0; 
            break; 
    } 
} 
//生成食物
function createFood(){
     var rdm_idx=randomNum(0,gameCellArray.length-1);//坐标随机索引
     var food_position=gameCellArray[rdm_idx];//食物产生的坐标
     var food_idx=randomNum(0,foodArray.length-1);//食物随机索引
     var food_id="food_"+food_position[0]+"_"+food_position[1];
     //console.log(food_position);
     //food_position=[39,33];
     var offsetX=food_position[0]*20;//X坐标的左偏移量
     var offsetY=food_position[1]*20;//Y坐标的上偏移量
     var food_html='<div id="'+food_id+'" class="food-position" style="left:'+offsetX+'px;top:'+offsetY+';"><svg class="icon" aria-hidden="true"><use xlink:href="'+foodArray[food_idx]+'"></use></svg></div>';
     $("#game-container").append(food_html);
     foodLocation.x=food_position[0];
     foodLocation.y=food_position[1];
}
//转向
function turnDirection(snakeObj,oldDir,newDir){    
    var tr=0;//转向,1-向左转(逆时针转),2向右转(顺时针转)    
    $(snakeObj.element).oldRotateDir=oldDir;
    if(oldDir==1 || oldDir==3){
        if(newDir==2){
            $(snakeObj.element).css({'-webkit-transform':'rotate(0deg)'});
            $(snakeObj.element).newRotateDir=2;
        }else if(newDir==4){
            $(snakeObj.element).css({'-webkit-transform':'rotate(180deg)'});
            $(snakeObj.element).newRotateDir=4;
        }
    }
    if(oldDir==2 || oldDir==4){
        if(newDir==1){
            $(snakeObj.element).css({'-webkit-transform':'rotate(-90deg)'});
            $(snakeObj.element).newRotateDir=1;
        }else if(newDir==3){
            $(snakeObj.element).css({'-webkit-transform':'rotate(90deg)'});
            $(snakeObj.element).newRotateDir=3;
        }
    }
}